package com.lezhi.socialgram.api.sys;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.friend.FriendMapper;
import com.lezhi.socialgram.mapper.moments.MomentMapper;
import com.lezhi.socialgram.mapper.sys.UserHobbyMapper;
import com.lezhi.socialgram.mapper.sys.UserMapper;
import com.lezhi.socialgram.mapper.sys.UserPrivacyMapper;
import com.lezhi.socialgram.model.friend.MyLike;
import com.lezhi.socialgram.model.moments.Moment;
import com.lezhi.socialgram.model.sys.*;
import com.lezhi.socialgram.service.sys.UserService;
import com.lezhi.socialgram.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by daizhen on 2017/4/19.
 */
@RestController
public class UserApi {

    private static final Logger logger = LoggerFactory.getLogger(UserApi.class);

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserMapper userMapper;

    @Autowired
    MomentMapper momentMapper;

    @Autowired
    FriendMapper friendMapper;

    @Autowired
    UserHobbyMapper userHobbyMapper;

    @Autowired
    UserPrivacyMapper userPrivacyMapper;

    @GetMapping("account/{userId}")
    public Result account(@PathVariable("userId") Long userId) {
        return userService.getAccountInfo(userId);
    }

    @GetMapping("newMsg/{userId}")
    public Result newMsg(@PathVariable("userId") Long userId) {
        try {
            Map<String, Object> newMsg = new HashMap();
            newMsg.put("new_like_me_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_LIKE_ME_COUNT));
            newMsg.put("new_like_my_moment_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_LIKE_MY_MOMENT_COUNT));
            newMsg.put("new_comment_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_COMMENT_COUNT));
            newMsg.put("new_gifts_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_GIFTS_COUNT));
            newMsg.put("new_at_me_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_AT_ME_COUNT));
            newMsg.put("new_collect_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_COLLECT_COUNT));
            newMsg.put("new_zf_count", stringRedisTemplate.opsForHash().get(userId + "user_count", Param.NEW_ZF_COUNT));
            return ResultUtils.success(newMsg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @GetMapping("clearNewMsg/{userId}")
    public Result clearNewMsg(@PathVariable("userId") Long userId) {
        try {
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_LIKE_ME_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_LIKE_MY_MOMENT_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_COMMENT_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_GIFTS_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_AT_ME_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_COLLECT_COUNT, "0");
            stringRedisTemplate.opsForHash().put(userId + "user_count", Param.NEW_ZF_COUNT, "0");
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @GetMapping("userInfo/{userId}/{myId}")
    public Result userInfo(@PathVariable("userId") Long userId, @PathVariable("myId") Long myId) {
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("table", TableUtils.getTableNameWithId(TelNumSignInUser.class, userId, 10));
            hashMap.put("userId", userId);
            User user = userMapper.queryUser(hashMap);
            user.setNickname(user.getNicknameZh());
            user.setIsVip(user.getVipExpireTime() == null ? 0 : (user.getVipExpireTime().after(new Date()) ? 1 : 0));
            user.setAge(XUtil.getAge(user.getBirthday()));
            user.setStarSign(XUtil.getConstellation(new Date()));

            MyLike myLike = new MyLike();
            myLike.setUid(myId);
            myLike.setFid(user.getUserId());
            myLike.setTable(TableUtils.getTableNameWithId(MyLike.class, myId, 100));
            MyLike like = friendMapper.queryMyLikeById(myLike);
            if (like != null) {
                user.setIsLike(1);
            } else {
                user.setIsLike(0);
            }

            UserHobby userHobby = new UserHobby();
            userHobby.setTable(TableUtils.getTableNameWithId(UserHobby.class, user.getUserId(), 10));
            userHobby.setUserId(user.getUserId());
            UserHobby hobby = userHobbyMapper.queryUserHobbyById(userHobby);
            user.setEating(hobby != null ? hobby.getFood() : Collections.EMPTY_LIST);
            user.setMovies(hobby != null ? hobby.getMovie() : Collections.EMPTY_LIST);
            user.setMusics(hobby != null ? hobby.getMusic() : Collections.EMPTY_LIST);
            user.setSports(hobby != null ? hobby.getSport() : Collections.EMPTY_LIST);

            UserPrivacy userPrivacy = new UserPrivacy();
            userPrivacy.setUserId(user.getUserId());
            userPrivacy.setTable(TableUtils.getTableNameWithId(UserPrivacy.class, user.getUserId(), 10));
            UserPrivacy privacy = userPrivacyMapper.queryById(userPrivacy);
            user.setForbidStrangeSendMsg(privacy != null ? privacy.getForbidStrangeLetter() : 0);

            Set<String> range = stringRedisTemplate.opsForZSet().range(user.getUserId() + ":tls", -1, -1);

            Object momentCount = stringRedisTemplate.opsForHash().get(user.getUserId() + "_info", "momentCount");
            user.setMomentCount(momentCount != null ? Integer.parseInt(momentCount + "") : 0);

            if (range != null && range.size() > 0) {
                String momentId = new ArrayList<>(range).get(0);
                if (momentId != null && momentId.contains("_")) {
                    String s = momentId.substring(0, momentId.indexOf("_"));
                    Date date = new Date(Long.parseLong(s));
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd");
                    String format = simpleDateFormat.format(date);
                    Moment moment = new Moment();
                    moment.setTable("t_moments_" + format);
                    moment.setMomentId(momentId);
                    moment = momentMapper.queryMomentById(moment);
                    user.setLastMomentContent(moment != null ? moment.getTextContent() : null);
                    user.setLastMomentImageUrl(moment != null ?
                            (moment.getMedia_list() != null && moment.getMedia_list().size() > 0 ?
                                    moment.getMedia_list().get(0).getImageUrl() : null) : null);
                    user.setLastMomentTimezone(moment != null ? moment.getCreateTime().getTime() : null);
                }
            }
            return ResultUtils.success(user);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }

    @PostMapping("/updateUserInfo")
    @Transactional
    public Result updateUserInfo(@RequestBody @Valid User_ user, BindingResult bindingResult) {
        ValidUtils.valid(logger, bindingResult);
        try {
            user.setTable(TableUtils.getTableNameWithId(User_.class, user.getUserId(), 10));
            userMapper.updateUserInfo(user);
            UserHobby userHobby = new UserHobby();
            userHobby.setUserId(user.getUserId());
            userHobby.setTable(TableUtils.getTableNameWithId(UserHobby.class, user.getUserId(), 10));
            userHobby.setSport(user.getSports());
            userHobby.setFood(user.getFoods());
            userHobby.setMusic(user.getMusics());
            userHobby.setMovie(user.getMovies());
            UserHobby hobby = userHobbyMapper.queryUserHobbyById(userHobby);
            if (hobby == null) {
                userHobbyMapper.insertUserHobby(userHobby);
            } else {
                userHobbyMapper.updateUserHobby(userHobby);
            }
            return ResultUtils.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }
}
